using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace LFromeWork
{
    public class UIManager : IDisposable
    {
        #region 属性

        //ui界面控制器列表
        List<UICtrlBase> m_UICtrlList = new List<UICtrlBase>();

        //基础画布
        public Canvas Canvas { get; private set; }

        //基础画布
        public CanvasScaler CanvasScaler { get; private set; }

        #endregion

        #region 初始化

        public void Init(Canvas canvas, CanvasScaler canvasScaler, int defaultWidth, int defaultHeight)
        {
            Canvas = canvas;
            CanvasScaler = canvasScaler;
            InitAdaptation(canvasScaler, defaultWidth, defaultHeight);
        }

        /// <summary>
        /// 通用适配
        /// </summary>
        public void InitAdaptation(CanvasScaler canvasScaler, int defaultWidth, int defaultHeight)
        {
            //0.5622
            float defaultValue = defaultWidth * 1.0f / defaultHeight;
            float currValue = Screen.width * 1.0f / Screen.height;

            if (currValue < defaultValue)
                canvasScaler.matchWidthOrHeight = 1;
            else
                canvasScaler.matchWidthOrHeight = 0;
        }

        #endregion

        public void AddUI(UICtrlBase uiCtrl)
        {
            if (m_UICtrlList.IndexOf(uiCtrl) >= 0) return;
            _OpenOneUI(uiCtrl);
        }
        
        public void RemoveUI(UICtrlBase uiCtrl)
        {
            m_UICtrlList.Remove(uiCtrl);
        }

        public void _OpenOneUI(UICtrlBase uiCtrl)
        {
            m_UICtrlList.Add(uiCtrl);
            
            uiCtrl.DoOpen();
        }

        /// <summary>
        /// 刷新Canvas order
        /// </summary>
        public void RefreshCanvasOrder()
        {
            for (int i = 0; i < m_UICtrlList.Count; ++i)
            {
                //间隔10
                m_UICtrlList[i].WindowOrder = (i + 1) * 10;
            }
        }

        public void Dispose()
        {
            m_UICtrlList.Clear();
            m_UICtrlList = null;
        }
    }
}
